import api from "@/api";
import type { CascadedAreaItem } from "@/types";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";

interface AreaStore {
	data: CascadedAreaItem[];
	getData: () => Promise<CascadedAreaItem[]>;
}

const useAreaStore = create<AreaStore>()(
	persist(
		(set) => ({
			data: [],
			getData: async () => {
				const response = await api.baseAreaGetCascadedAreasList();
				// @ts-ignore
				const data: CascadedAreaItem[] = response.map((x) => ({
					code: x.code!,
					name: x.name!,
					children:
						x.children?.map((y) => ({
							code: y.code!,
							name: y.name!,
							children:
								y.children?.map((z) => ({
									code: z.code!,
									name: z.name!,
								})) ?? null,
						})) ?? null,
				}));
				set({ data });
				return data;
			},
		}),
		{
			name: "areas",
			storage: createJSONStorage(() => localStorage),
		},
	),
);

export default useAreaStore;
